
package com.hnas.eastsquare.util;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.hnas.core.util.StringUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
/**
 * 集群的redis
 * @author Administrator
 *
 */
@Component("jedisPoolUtil")
public class JedisPoolUtil {
	
	
	private static String redis_master_name;
	
	private static String redis_password;
	
	private static String redis_sentinals;

	private static JedisSentinelPool pool = null;
	
	@Value("#{component['redis_master_name']}")
	public void setRedis_master_name(String redis_master_name) {
		JedisPoolUtil.redis_master_name = redis_master_name;
	}
	@Value("#{component['redis_password']}")
	public void setRedis_password(String redis_password) {
		JedisPoolUtil.redis_password = redis_password;
	}
	@Value("#{component['redis_sentinals']}")
	public void setRedis_sentinals(String redis_sentinals) {
		JedisPoolUtil.redis_sentinals = redis_sentinals;
	}
	/**
	 * 创建连接池
	 *
	 */
	private static void createJedisPool() {

		Set<String> sentinels = new HashSet<String>();
		if(StringUtil.isEmpty(redis_sentinals)) return;
		String[] sentinalArr = redis_sentinals.split(",");
		for(String sentinal : sentinalArr) {
			sentinels.add(sentinal);
		}
		/* 测试环境哨兵：
		 * 	sentinel.1=172.16.20.207:26379
		 * 	sentinel.2=172.16.20.202:26379
		 * 	sentinel.3=172.16.20.170:26379
		 */
//		sentinels.add("10.28.93.52:26379");
//		sentinels.add("10.28.93.254:26379");
//		sentinels.add("10.28.93.254:36379");
//		sentinels.add("10.28.93.254:46379");
		pool = new JedisSentinelPool(redis_master_name, sentinels, redis_password);
	}
	/**
	 * 在多线程环境同步初始化
	 */
	private static synchronized void poolInit() {
		if (pool == null)
			createJedisPool();
	}

	/**
	 * 获取一个jedis 对象
	 *
	 * @return
	 */
	public static Jedis getJedis() {
		if (pool == null)
			poolInit();
		return pool.getResource();
	}

	/**
	 * 释放一个连接
	 *
	 * @param jedis
	 */
	public static void returnRes(Jedis jedis) {
		try {
			pool.returnResource(jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 销毁一个连接
	 *
	 * @param jedis
	 */
	public static void returnBrokenRes(Jedis jedis) {
		try {
			pool.returnBrokenResource(jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
